const jwt = require('jsonwebtoken')

const { JWT_SECRET } = require('../config/config.default')

const {
  tokenExpiredError,
  invalidToken,
  hasNotAdminPermission,
} = require('../constant/err.type')

const auth = async (ctx, next) => {
  const { authorization = '', webmark} = ctx.request.header
  console.log(ctx.request.header)

  if(webmark === 'noToekn') {
    await next()
  } else {
    const token = authorization.replace('Bearer ', '')
    try {
      const user = jwt.verify(token, JWT_SECRET)
      ctx.state.user = user
    } catch(err) {
      switch (err.name) {
        case 'TokenExpiredError':
          console.error('token已过期', err)
          // return ctx.app.emit('error', tokenExpiredError, ctx)
          ctx.response.body = tokenExpiredError
          return 
        case 'JsonWebTokenError':
          console.error('无效的token', err)
          // return ctx.app.emit('error', invalidToken, ctx)
          ctx.response.body = invalidToken
          return 
      }
    }
    
    await next()
  }
  
}


module.exports = {
  auth
}